//
//  ZTool.m
//  DingDing
//
//  Created by Anissa on 14-4-9.
//  Copyright (c) 2014年 Cstorm. All rights reserved.
//

#import "ZTool.h"

#include <ifaddrs.h>
#include <arpa/inet.h>
#include <net/if.h>

#define IOS_CELLULAR    @"pdp_ip0"
#define IOS_WIFI        @"en0"
#define IOS_VPN         @"utun0"
#define IP_ADDR_IPv4    @"ipv4"
#define IP_ADDR_IPv6    @"ipv6"

@implementation ZTool

+(BOOL)isValidateFamilyName:(NSString *)familyName{
    NSString *nameRegex = @"[\u4e00-\u9fa5]{1,2}";
    NSPredicate *nameTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",nameRegex];
    return [nameTest evaluateWithObject:familyName];
}

+(BOOL)isValidateName:(NSString *)name{
    NSString *nameRegex = @"[\u4e00-\u9fa5]{2,4}";
    NSPredicate *nameTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",nameRegex];
    return [nameTest evaluateWithObject:name];
}

+(BOOL)isValidateNickname:(NSString *)nickname{
    NSString *nameRegex = @"^[\u4e00-\u9fa5a-zA-Z0-9]+$";
    NSPredicate *nameTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",nameRegex];
    return [nameTest evaluateWithObject:nickname];
}

+(BOOL)isValidateEmail:(NSString *)email{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}
+(BOOL)isValidatePhone:(NSString *)phone{
    NSString *phoneRegex = @"(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1})|(14[0-9]{1}))+\\d{8})";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
    return [phoneTest evaluateWithObject:phone];
}
+(BOOL)isValidatePassword:(NSString *)pwd{
    NSString *pwdRegex = @"^[A-Z0-9a-z]{6,16}$";
    NSPredicate *pwdTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pwdRegex];
    return [pwdTest evaluateWithObject:pwd];
}

+(BOOL)isValidateInteger:(NSString *)string{
    NSString *integerRegex = @"[1-9][0-9]{0,20}";
    NSPredicate *integerTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",integerRegex];
    return [integerTest evaluateWithObject:string];
}
+(BOOL)isValidateVehicleNumber:(NSString *)vehicleNumber{
    NSString *vehicleNumRegex = @"[\u4e00-\u9fa5]{1}[A-Z]{1}[A-Z_0-9]{5}";
    NSPredicate *vehicleNumTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",vehicleNumRegex];
    return [vehicleNumTest evaluateWithObject:vehicleNumber];
}

+(BOOL)isIphone4s{
    return [UIScreen mainScreen].bounds.size.height==480;
}
+ (BOOL)isIphone5
{
    return ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 1136), [UIScreen mainScreen].currentMode.size) : NO);
}
+(BOOL)isIphone6{
    return ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(375*2, 667*2), [UIScreen mainScreen].currentMode.size) : NO);
}
+(BOOL)isIphone6p{
    return ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(414*3, 736*3), [UIScreen mainScreen].currentMode.size) : NO);
}
+(BOOL)isMoreThanIphone5s{
    return ![self isIphone4s] && ![self isIphone5];
}

+ (NSString *)safeString:(NSString *)string
{
    if (!string || [string isKindOfClass:[NSNull class]] || ![string isKindOfClass:[NSString class]]){
        return @"";
    }
    return string;
}


+ (CGSize)sizeWithText:(NSString *)text font:(UIFont *)font constrainedToSize:(CGSize)size
{
    CGSize textSize = CGSizeZero;
    
#if __IPHONE_OS_VERSION_MAX_ALLOWED <= __IPHONE_7_0
    
    textSize = [text sizeWithFont:font constrainedToSize:size];
    
#else
    
    NSDictionary * tdic = @{NSFontAttributeName: font};
    textSize = [text boundingRectWithSize:size
                                  options:NSStringDrawingUsesLineFragmentOrigin
                               attributes:tdic
                                  context:nil].size;
#endif
    
    return textSize;
}

+ (void)showAlertWithMessage:(NSString *)message {
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    UILabel *alertLabel = (UILabel *)[window viewWithTag:50000];
    CGFloat fontSize = 14.0f;
    if( alertLabel ){
        [alertLabel removeFromSuperview];
        alertLabel = nil;
    }
    
    alertLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    alertLabel.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
    alertLabel.textColor = [[UIColor whiteColor] colorWithAlphaComponent:0.9];
    alertLabel.layer.cornerRadius = 3;
    alertLabel.layer.masksToBounds = YES;
    alertLabel.tag = 50000;
    alertLabel.numberOfLines = 0;
    alertLabel.textAlignment = NSTextAlignmentCenter;
    alertLabel.font = [UIFont systemFontOfSize:fontSize];
    [window addSubview:alertLabel];
    alertLabel.text = message;
    [alertLabel sizeToFit];
    
    if( message && message.length ){
        CGRect frame = alertLabel.frame;
        if( frame.size.width >  window.bounds.size.width-50 ){
            frame.size.width = window.bounds.size.width-50;
        }else{
            frame.size.width += 20;
        }
        frame.size.height = [message boundingRectWithSize:CGSizeMake(frame.size.width, MAXFLOAT) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]} context:nil].size.height+15;
        frame.origin.x = (window.bounds.size.width-frame.size.width)/2.0f;
        frame.origin.y = window.bounds.size.height-frame.size.height-80;
        alertLabel.frame = frame;
    }
    
    [alertLabel performSelector:@selector(removeFromSuperview) withObject:nil afterDelay:1.5f];
}


+(void)showFunctionInstruction{
    [self showAlertWithMessage:@"小伙伴儿正在加急开发中，敬请期待!"];
}

+(NSArray *)allCharacters{
    return @[@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z"];
}

+(NSString *)formatInterger:(NSInteger)number{
    if( number>=10 ){
        return [NSString stringWithFormat:@"%ld",(long)number];
    }else if(number>=0){
        return [NSString stringWithFormat:@"0%ld",(long)number];
    }
    return @"00";
}

+(NSString *)jsonStringFromDictionary:(NSDictionary *)dic{
    NSArray *keys = dic.allKeys;
    NSArray *values = dic.allValues;
    
    NSMutableString *result = [NSMutableString string];
    for (NSInteger i=0; i<keys.count; i++) {
        if( i==keys.count-1 ){
            if( [values[i] hasPrefix:@"{"] && [values[i] hasSuffix:@"}"] ){
                [result appendFormat:@"\"%@\":%@",keys[i],values[i]];
            }else{
                [result appendFormat:@"\"%@\":\"%@\"",keys[i],values[i]];
            }
        }else{
            if( [values[i] hasPrefix:@"{"] && [values[i] hasSuffix:@"}"] ){
                [result appendFormat:@"\"%@\":%@,",keys[i],values[i]];
            }else{
                [result appendFormat:@"\"%@\":\"%@\",",keys[i],values[i]];
            }
        }
    }
    result = [[[@"{" stringByAppendingString:result] stringByAppendingString:@"}"] copy];
    return result;
}


//获取手机设备的ip地址
+ (NSString *)getDeviceIPAddress:(BOOL)preferIPv4 {
    NSArray *searchArray = preferIPv4 ?
    @[ IOS_VPN @"/" IP_ADDR_IPv4, IOS_VPN @"/" IP_ADDR_IPv6, IOS_WIFI @"/" IP_ADDR_IPv4, IOS_WIFI @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6 ] :
    @[ IOS_VPN @"/" IP_ADDR_IPv6, IOS_VPN @"/" IP_ADDR_IPv4, IOS_WIFI @"/" IP_ADDR_IPv6, IOS_WIFI @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4 ] ;
    
    NSDictionary *addresses = [self getIPAddresses];
    
    __block NSString *address;
    [searchArray enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL *stop)
     {
         address = addresses[key];
         if(address) *stop = YES;
     } ];
    return address ? address : @"0.0.0.0";
}

+ (NSDictionary *)getIPAddresses
{
    NSMutableDictionary *addresses = [NSMutableDictionary dictionaryWithCapacity:8];
    
    // retrieve the current interfaces - returns 0 on success
    struct ifaddrs *interfaces;
    if(!getifaddrs(&interfaces)) {
        // Loop through linked list of interfaces
        struct ifaddrs *interface;
        for(interface=interfaces; interface; interface=interface->ifa_next) {
            if(!(interface->ifa_flags & IFF_UP) /* || (interface->ifa_flags & IFF_LOOPBACK) */ ) {
                continue; // deeply nested code harder to read
            }
            const struct sockaddr_in *addr = (const struct sockaddr_in*)interface->ifa_addr;
            char addrBuf[ MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) ];
            if(addr && (addr->sin_family==AF_INET || addr->sin_family==AF_INET6)) {
                NSString *name = [NSString stringWithUTF8String:interface->ifa_name];
                NSString *type;
                if(addr->sin_family == AF_INET) {
                    if(inet_ntop(AF_INET, &addr->sin_addr, addrBuf, INET_ADDRSTRLEN)) {
                        type = IP_ADDR_IPv4;
                    }
                } else {
                    const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6*)interface->ifa_addr;
                    if(inet_ntop(AF_INET6, &addr6->sin6_addr, addrBuf, INET6_ADDRSTRLEN)) {
                        type = IP_ADDR_IPv6;
                    }
                }
                if(type) {
                    NSString *key = [NSString stringWithFormat:@"%@/%@", name, type];
                    addresses[key] = [NSString stringWithUTF8String:addrBuf];
                }
            }
        }
        // Free memory
        freeifaddrs(interfaces);
    }
    return [addresses count] ? addresses : nil;
}

@end
